import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/http/http_interceptor.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/config/app_start.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/global_context.dart';

import 'common/log/x_logger.dart';
import 'common/push/jpush_utils.dart';

Future<void> _initAppConfig() async {
  print('Appstart 初始化');
  try {
    await JPushUtils.initJPush();
    print('JPushUtils 初始化');

    await AppStart.initConfig();
    // 初始化完成后，可以触发状态更新（例如通知 Provider）
    // await AppStart.showMapConfig();   // 控制地图与huawei 的显示
    // 初始化极光推送

    // 例如：通过 Provider 监听配置变化
  } catch (e) {
    // 处理错误
    print('Appstart 初始化失败: $e');
  }
}
void main() async {
  //不加这个强制横/竖屏会报错
  WidgetsFlutterBinding.ensureInitialized();
  // 禁止横屏
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  Env.initEnvConfig();
  // 等待sp初始化完成后再运行app。
  // sp初始化时间 release模式下30ms左右，debug模式下100多ms。
  await SpUtil.getInstance();

  if (Platform.isAndroid) {
    final isAgree = SpUtil.getBool('hasAgreed') ?? false;
    XLogger.debug('isAgree :$isAgree');
    if (isAgree) {
      await _initAppConfig();
    }
  }else {
    await _initAppConfig();
  }

  NetOptions.instance
      .setBaseUrl(Env.envConfig.apiBaseUrl)
      .setConnectTimeout(const Duration(seconds: 5))
      // .setHttpDecoder(MyHttpDecoder.getInstance())
      .addInterceptor(HttpInterceptor())
      .enableLogger(true)
      .create();

  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context, WidgetRef ref) {

    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 点击空白处收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: MaterialApp.router(
        key: NavigationService.navigatorKey,
        title: Env.envConfig.appName,
        locale: const Locale('zh', 'CN'),
        localizationsDelegates: const [
          // 本地化的代理类
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: const [
          // 支持的本地化语言
          Locale('zh', 'CN'),
        ],
        themeMode: ThemeMode.light,
        darkTheme: ThemeData.light(),
        // 关闭debug标签
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          brightness: Brightness.light,
          // primarySwatch: Colors.blue,
          // primaryColor: ColorUtils.hexToColor("#165DFF"),
          // colorSchemeSeed: ColorUtils.hexToColor("#165DFF"),
          textTheme: TextTheme(
            bodyMedium: TextStyle(color: ColorUtils.hexToColor("#333333")),
            bodySmall: TextStyle(color: ColorUtils.hexToColor("#666666")),
          ),
          useMaterial3: true,
          colorScheme:
              ColorScheme.fromSeed(seedColor: ColorUtils.hexToColor("#165DFF")).copyWith(surfaceTint: Colors.white),
          appBarTheme: AppBarTheme(
            iconTheme: IconThemeData(color: Colors.black), // 设置AppBar中图标（包括返回按钮）颜色为黑色
            titleTextStyle: TextStyle(color: ColorUtils.hexToColor("#009FE8")), // 设置AppBar标题文本颜色为蓝色
          ),
        ),

        routerConfig: RouterManager.routerConfig,
        builder: EasyLoading.init(builder: (context, child) {
          return MediaQuery(
            data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
            child: child ?? Container(),
          );
        }),
      ),
    );
  }
}
